<script setup lang="ts">
import { ref,watch} from 'vue'
import VuePdfEmbed from 'vue-pdf-embed'
import { ZoomInOutlined,ZoomOutOutlined,RotateRightOutlined,DownloadOutlined} from '@ant-design/icons-vue'
import {serverUrl} from "@/common/config"
import {downloadFileByBlob} from "@/common/utils"
import {getReq} from "@/common/request"
import Icon from '@/components/icon/icon.vue'
 
/* 
体积很大，有1.63mb，不是特别推荐使用，或者可以使用cdn
<scrip src="https://unpkg.com/vue-pdf-embed"></scrip>，此时组件名称必须是 VuePdfEmbed


 PDF.js ，一个完整的 PDF 查看器，可以直接使用其提供的 viewer.html 查看 PDF 内容，包含完整样式和相关功能。优点是快速集成，不需要自己实现查看器的功能和样式。缺点是如果要自定义样式和功能，反而会很麻烦。体积很大有10mb，下载地址：https://mozilla.github.io/pdf.js/getting_started/
pdfjs-dist ，PDF.js 的预购建版本，只包含 PDF 内容的渲染功能，需要自己实现查看器的样式和相关功能，定制性更强，体积也相对较小。
如果要求不高直接使用iframe最好
*/


const props=withDefaults(defineProps<{
  url?:string
}>(),{
  url:'http://localhost:5000/pdfs/test1.pdf',
})

const pdfRef = ref<any>()
const pageCount = ref(1)
const currentPage = ref<any>(1)
const showAllPages = ref(false)
const rotations = [0, 90, 180, 270]
const currentRotation = ref(0)
const scale = ref<number>(1)
const scaleUnit = 0.1
const visible = ref(false)
const inputCurrentPage=ref(1)
const pdfUrl = ref<any>()
const progress=ref(0)
const pdfLoading=ref(false)


watch(()=>props.url,(url)=>{
  //.log(url,url.split('http://localhost:5000'))
  pdfUrl.value=`${import.meta.env.VITE_BASE_URL}${url.split(serverUrl)[1]}`
},{immediate:true})


watch(visible,(visible)=>{
   
})

//console.log(VuePdfEmbed.getDocument)
const handleRendered = () => {
	pageCount.value = pdfRef.value.pageCount
  pdfLoading.value=false
  //console.log(pdfRef.value)
}

const hanldeJump=()=>{
   currentPage.value=inputCurrentPage.value
}

// `${parseInt((scale * 100).toFixed(2))}%`
const handleZoom=(isUp:boolean)=>{
  if(isUp) scale.value=Number((scale.value+scaleUnit).toFixed(1))
  else {
    if(scale.value>scaleUnit) scale.value=Number((scale.value-scaleUnit).toFixed(1)) 
  }
}

const handleRotate=()=>{
  if(currentRotation.value==rotations.length)  {
    currentRotation.value=0
    return
  }
  currentRotation.value++
}

const handleDownload=async()=>{
   const res=await getReq(props.url.split(serverUrl)[1],{},{responseType: 'blob',GetWholeResponse:true})
   //console.log(res)
   downloadFileByBlob(res,'test1.pdf')
}

const handleShowAllPagesChange = () => {
	currentPage.value = showAllPages.value ? null : 1
}

const handlePrint = () => {
	pdfRef.value.print()
}

const onprogress=(e:any)=>{
  pdfLoading.value=true
  progress.value=parseInt(String((e.loaded/e.total))) * 100
}


const changeUrl=()=>{
   pdfUrl.value=`${import.meta.env.VITE_BASE_URL}/pdfs/test.pdf`
   pdfRef.value.render()
}
</script>

<template>
	<a-button type="primary" @click="visible = true">open pdf</a-button>
	
	<a-modal v-model:visible="visible" title="pdf预览" centered :footer="null" width="70%" :bodyStyle="{minHeight:'88vh',maxHeight:'88vh',overflow:'auto'}">
    <!-- <a-button type="primary" @click="changeUrl">change url</a-button> -->
    <div class="tools">
      <div style="margin-right: 50px;" v-show="!showAllPages">
        <a-input-number v-model:value="inputCurrentPage" @step="hanldeJump"  @pressEnter="hanldeJump" :min="1" :max="pageCount" style="width: 60px;" />  / <span>{{ pageCount }}</span>
      </div>
       
      <div style="margin-right: 50px;">
        <zoom-in-outlined  class="icon"  @click="handleZoom(true)" />
        <span style="margin: 0 5px;">{{`${(scale * 100).toFixed(0)}%`}}</span>
        <zoom-out-outlined class="icon" @click="handleZoom(false)"/>
      </div>
     
      <rotate-right-outlined  class="icon" style="margin-right: 50px;"  @click="handleRotate"   />
     
      <download-outlined class="icon" style="margin-right: 50px;" @click="handleDownload" />

      <Icon name="print" width="23px" height="23px" style="margin-right: 50px;cursor: pointer;"  @click="handlePrint"  />
      
      <a-tooltip>
        <template #title>{{ showAllPages?'展示单页':'展示所有' }}</template>
        <a-switch v-model:checked="showAllPages" size="small" style="margin-right: 50px;" @change="handleShowAllPagesChange"/>
      </a-tooltip>
    </div>
    
    <a-progress type="circle" :width="50" :percent="progress" v-show="pdfLoading"  class="loading" />
		
    <vue-pdf-embed class="pdf" ref="pdfRef" :rotation="rotations[currentRotation]" :scale="scale" :page="currentPage" :source="pdfUrl" @rendered="handleRendered"  @progress="onprogress"
     @loading-failed="()=>{pdfLoading=false}"  @rendering-failed="()=>{pdfLoading=false}"  
    />
		<!--
          属性
          ref:用于获取pdf预览实例。
          rotation:视图旋转的角度
          page：当前所处页码，为null时不分页
          source：pdf地址
          width,height
          scale:缩放倍数.有理数 	所需的画布大小与文档大小的比率   没看懂
           
          事件
           loading-failed    错误对象        加载失败
           loaded            PDF文档代理     加载完成
           rendering-failed  错误对象       渲染失败
           rendered            无            渲染完成
           progress          进度参数对象       加载进度
           printing-failed    错误对象          打印失败
          password-requested   回调函数，重试标志        需要密码才能显示文档 

         实例静态方法
         render  刷新，手动渲染
         print   打印

        -->
	</a-modal>
</template>

<style scoped>

.tools{
  display: flex;
  align-items: center;

  position: sticky;
  top: 0;
  z-index: 999999999999999;
  user-select: none;

  .icon{
    cursor: pointer;
    font-size: 20px;
    color: gray;
  }
}

.loading{
   position: absolute;
   left: 50%;
   top: 50%;
   transform: translate(-50%,-50%);
   z-index: 99999;
}

</style>
